package com.zjp.reflect;

import com.zjp.entity.Student;
import com.zjp.entity.Teacher;

import java.io.FileOutputStream;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;

/**
 * @author: zjp
 * @date: 2023-12-02
 * @description: 测试保存对象的信息到文件中
 */
public class Test5_SaveObjectInfoToFile {
    public static void main(String[] args) throws Exception {
        Student student = new Student(1, "zjp", 18, "男", "123@qq.com");
        Teacher teacher = new Teacher("zyy", BigDecimal.ONE);
        saveObjectInfoToFile(student);
        saveObjectInfoToFile(teacher);
    }

    // 工具方法，通过反射获取对象的信息并输出到文件中
    public static void saveObjectInfoToFile(Object obj) throws Exception {
        if (obj != null){
            // 定义一个打印流，用来向文件写入数据
            PrintStream ps = new PrintStream(new FileOutputStream("src\\info.txt", true));
            // 1.获取对象对应的类的信息
            Class<?> clazz = obj.getClass();

            String className = clazz.getSimpleName(); // 类名
            ps.println("----------------" + className + "-----------------");
            // 2.获取所有属性
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true); // 放开访问权限
                String fName = field.getName(); // 属性名
                String fValue = field.get(obj) + ""; // 属性值

                ps.println(fName + " = " + fValue);
            }

            // 关闭打印流
            ps.close();
            System.out.println("输出完毕！");
        }
    }
}
